package br.com.post.persistence;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.post.model.Evaluation;

public class EvaluationDao {
	private static EvaluationDao instance;
	/**
	 * Persiste a avaliacao no banco
	 * @param evaluation
	 */
	public void createEvaluation(Evaluation evaluation) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(evaluation);
		tx.commit();
		session.close();
	}
	
	/**
	 * Atualiza a avaliacao no banco
	 * @param evaluation
	 */
	public void updateEvaluation(Evaluation evaluation) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.merge(evaluation);
		tx.commit();
		session.close();
	}
	
	/**
	 * Seleciona uma avaliacao no banco de acordo com o id(long)
	 * @param evaluation_id
	 * @return evaluation
	 */
	public Evaluation selectEvaluation(long evaluation_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Evaluation evaluation = (Evaluation)session.get(Evaluation.class,evaluation_id);
		tx.commit();
		session.close();
		return evaluation;
	}
	
	/**
	 * Deleta a avaliacao de acordo com o id, primeiro faz um select
	 * para o hibernate entender, depois remove a avaliacao selecionada
	 * @param evaluation_id
	 */
	public void deleteEvaluation(long evaluation_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Evaluation evaluation = selectEvaluation(evaluation_id);
		session.delete(evaluation);
		tx.commit();
		session.close();
	}

	public static EvaluationDao getInstance() {
		if(instance == null)
			instance = new EvaluationDao();
		return instance;
	}

	public static void setInstance(EvaluationDao instance) {
		EvaluationDao.instance = instance;
	}
	
}

